package com.vanysoft.business.system.init.service;

import com.vanysoft.business.base.org.dao.BaseOrgMapper;
import com.vanysoft.business.base.org.entity.TBaseOrg;
import com.vanysoft.business.base.user.dao.BaseOrgUsersMapper;
import com.vanysoft.business.base.user.dao.BaseUserMapper;
import com.vanysoft.business.base.user.dao.BaseUserRolesMapper;
import com.vanysoft.business.base.user.entity.TBaseOrgUsers;
import com.vanysoft.business.base.user.entity.TBaseUser;
import com.vanysoft.business.base.user.entity.TBaseUserRoles;
import com.vanysoft.business.system.init.controller.demo.RootOrgSetObj;
import com.vanysoft.business.system.init.dao.SystemInitMapper;
import com.vanysoft.business.system.license.dao.TSystemLicenseMapper;
import com.vanysoft.business.system.license.entity.TSystemLicense;
import com.vanysoft.business.system.loginSettings.dao.TSystemLoginSetMapper;
import com.vanysoft.business.system.loginSettings.entity.TSystemLoginSet;
import com.vanysoft.common.utils.Des.VanySoftLicenseUtil;
import com.vanysoft.common.utils.desc.DescUtil;
import com.vanysoft.framework.exception.VanySoftBaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Date;
import java.util.UUID;

/**
 * 类名称：SystemInitService
 * 类描述：系统初始化向导
 * 创建人：X
 * 创建时间：2017年9月19日下午10:08:11
 * 修改人：X
 * 修改时间：2017年9月19日
 * 版本信息：@version 1.0
 * Copyright (c) 2017SharpClaw-版权所有
 * 修改备注：
 */
@Service
@Transactional(readOnly = true)
public class SystemInitService {

    @Autowired
    private SystemInitMapper systemInitMapper;
    @Autowired
    private BaseUserMapper baseUserMapper;
    @Autowired
    private BaseOrgMapper baseOrgMapper;
    @Autowired
    private BaseOrgUsersMapper baseOrgUsersMapper;
    @Autowired
    private BaseUserRolesMapper baseUserRolesMapper;
    @Autowired
    private TSystemLoginSetMapper tSystemLoginSetMapper;

    @Autowired
    private TSystemLicenseMapper tSystemLicenseMapper;

    /**
     * Function Name               initSystemTable
     *
     * @param loginDemo
     * @return
     * @throws VanySoftBaseException
     * @description 初始化系统设置表结构方法
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年9月19日下午1:26:50          X          Initial
     * *********************************************************************
     */
    @Transactional
    public boolean initSystemTable() throws VanySoftBaseException {
        boolean b = true;
        try {
            File file = ResourceUtils.getFile("classpath:sql/createtables.sql");
            BufferedReader br = new BufferedReader(new FileReader(file));
            StringBuffer sqlBuffer = new StringBuffer();
            while (true) {
                String str = br.readLine();
                if (str == null) {
                    break;
                }
                System.out.println(str);
                sqlBuffer.append(str);
            }
            br.close();
            String sqls[] = sqlBuffer.toString().split(";");
            for (String execSql : sqls) {
                try {
                    systemInitMapper.execSql(execSql);
                } catch (Exception e) {
                    b = false;
                }
            }
        } catch (Exception e) {
            b = false;
        } finally {
            return b;
        }
    }

    /**
     * Function Name               initSystem
     *
     * @return
     * @throws VanySoftBaseException
     * @description 初始化系统设置数据方法
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年9月19日上午10:19:10          X          Initial
     * *********************************************************************
     */
    @Transactional
    public boolean initSystemData(RootOrgSetObj inputObj) throws VanySoftBaseException {
        boolean b = true;
        try {
            //step1:生成系统序列号以及序列号对应的试用注册码（操作T_System_License表）
            String serialNoBegin = "ac25-cb91";
            String systemSN = serialNoBegin + UUID.randomUUID().toString().substring(9);
            String license = VanySoftLicenseUtil.createTestLicense(systemSN);
            TSystemLicense obj = new TSystemLicense();
            obj.setSystemSN(systemSN);
            obj.setLicense(license);
            tSystemLicenseMapper.deleteLicense();
            tSystemLicenseMapper.insert(obj);
            //step2:生成组织机构和用户信息（T_Base_User,T_Base_OrgUsers,T_Base_Org,T_Base_UserRoles）
            String userId = UUID.randomUUID().toString();
            String orgCode = "000000";
            String orgUserId = UUID.randomUUID().toString();
            String userRoleId = UUID.randomUUID().toString();
            String roleCode = "ADMINISTRATORS";
            String userPassword = DescUtil.encrypt(inputObj.getUserPassword());
            String yesStr = "1";
            TBaseUser user = new TBaseUser();
            user.setUserId(userId);
            user.setUserAccount(inputObj.getUserAccount());
            user.setUserName(inputObj.getUserAccount());
            user.setUserPassword(userPassword);
            user.setIsCustomer(yesStr);
            user.setStatus(yesStr);
            user.setUpdateTime(new Date());
            user.setIsAvailable(yesStr);
            user.setEmail(inputObj.getUserEmail());
            TBaseOrg org = new TBaseOrg();
            org.setOrgCode(orgCode);
            org.setOrgName(inputObj.getOrgName());
            org.setSearchKeyWord1(inputObj.getOrgName());
            org.setSearchKeyWord2(inputObj.getOrgName());
            org.setUpdateTime(new Date());
            org.setIsAvailable(yesStr);
            TBaseUserRoles userRoles = new TBaseUserRoles();
            userRoles.setUserId(userId);
            userRoles.setUserRoleId(userRoleId);
            userRoles.setRoleCode(roleCode);
            TBaseOrgUsers orgUsers = new TBaseOrgUsers();
            orgUsers.setOrgUserId(orgUserId);
            orgUsers.setOrgCode(orgCode);
            orgUsers.setUserId(userId);
            orgUsers.setUserOrderNumber("1");
            baseUserMapper.insert(user);
            baseOrgMapper.insert(org);
            baseOrgUsersMapper.insert(orgUsers);
            baseUserRolesMapper.insert(userRoles);
            //step3:初始化登录安全设置信息（T_System_LoginSetting）
            TSystemLoginSet systemLoginSet = new TSystemLoginSet();
            String setId = UUID.randomUUID().toString();
            systemLoginSet.setSetId(setId);
            systemLoginSet.setErrorCount(3);
            systemLoginSet.setLimitLoginTime(30);
            systemLoginSet.setIsAvailable(yesStr);
            systemLoginSet.setCreateTime(new Date());
            tSystemLoginSetMapper.insert(systemLoginSet);
            //step4:删除安装向导功能菜单
            systemInitMapper.deleteSystemInitMenu();
            //step5:批量执行文件中的数据SQL语句
            File file = ResourceUtils.getFile("classpath:sql/initdatas.sql");
            BufferedReader br = new BufferedReader(new FileReader(file));
            StringBuffer sqlBuffer = new StringBuffer();
            while (true) {
                String str = br.readLine();
                if (str == null) {
                    break;
                }
                System.out.println(str);
                sqlBuffer.append(str);
            }
            br.close();
            String sqls[] = sqlBuffer.toString().split(";");
            for (String execSql : sqls) {
                try {
                    systemInitMapper.execSql(execSql);
                } catch (Exception e) {
                    b = false;
                }
            }
        } catch (Exception e) {
            b = false;
        } finally {
            return b;
        }
    }

}
